 var facebookGraphURL = 'https://graph.facebook.com/';

window.fbAsyncInit = function() {
  FB.init({
    appId      : '397790196975480', // App ID
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  FB.Event.subscribe('auth.statusChange', handleStatusChange);

  FB.getLoginStatus(function(response) {
    if (response.status === 'connected') {
      document.body.className = 'connected';
    }
    else {
      document.body.className = 'not_connected';
    } 
  });

  function handleStatusChange(response) {
    document.body.className = response.authResponse ? 'connected' : 'not_connected';
    if (response.authResponse) {
      console.log(response);

      getUserFeed();
    }
  }

  $('#btnNext').on('click', function(e) {
    getUserFeed($(this).data('until'));
  });

  $('#btnPrevious').on('click', function(e) {
    getUserFeed(null, $(this).data('since'));
  });
};

function loginUser() {
  FB.login(function(response) { }, {scope:'read_stream'});     
}

function getUserFeed(until, since) {
  var feedURL = '/me/feed';
  if (until) {
    feedURL += '?until=' + until;
  }
  else if (since) {
    feedURL += '?' + since;
  }
  FB.api(feedURL, function(response) {
    console.log('Got home feed: ', response);
    var feedArray = response.data;
    if (feedArray) {
      var $wallPostTemplate = $('#wallPostTemplate');
      var $lstvwWallFeed = $('#lstvwWallFeed');
      $lstvwWallFeed.find('li:gt(1)').remove();
      $wallPostTemplate.show();
      for (var i = 0; i < feedArray.length; i++) {
        console.log(feedArray[i]);
        var $wallPostItem = $wallPostTemplate.clone();
        var updateDate = new Date(feedArray[i].updated_time);
        console.log(updateDate);
        $wallPostItem
          .removeAttr('id')
          .find('div.userImage img').attr('src', facebookGraphURL + feedArray[i].from.id + '/picture?type=square').attr('alt', feedArray[i].from.name).end()
          .find('div.postInformation div.postUser').text(feedArray[i].from.name).end()
          .find('div.postInformation div.lastUpdatedTime').text(updateDate.getMonth() + '/' + updateDate.getDate() + '/' + updateDate.getFullYear());
        
        if (feedArray[i].story) {
          $wallPostItem.find('div.postInformation div.postText').text(feedArray[i].story);
        }
        else if (feedArray[i].message) {
           $wallPostItem.find('div.postInformation div.postText').text(feedArray[i].message);
        }

        if (feedArray[i].picture) {
          $wallPostItem.find('div.postMedia').html($('<img />').attr('src', feedArray[i].picture).attr('alt', feedArray[i].from.name + '\'s picture'));
        }

        $lstvwWallFeed.append($wallPostItem);
      };

      $wallPostTemplate.hide();
      if (response.paging.next) {
        $('#btnNext').data('until', getURLParameter(response.paging.next, 'until'));
      }
      if (response.paging.previous) {
        $('#btnPrevious').data('since', '&limit=25&since' + getURLParameter(response.paging.previous, 'since') + '&__previous=1');
      }
    }
  });
}

function getURLParameter(urlString, name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(urlString)||[,null])[1]
    );
}

// Load the SDK Asynchronously
(function(d) {
  var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
  if (d.getElementById(id)) {
    return;
  }
  js = d.createElement('script'); js.id = id; js.async = true;
  js.src = "//connect.facebook.net/en_US/all.js";
  ref.parentNode.insertBefore(js, ref);
}(document));